<template>
  <div class="hello">
    <div class="login" v-if="!isChat">
      <h1 >欢迎访问在线聊天室</h1>
      <el-form style="margin-top: 30px;position: relative" v-if="!isChat" :rules="rules" ref="from" :inline="true" :model="from">
        <el-form-item label="用户名" prop="fromName">
          <input class="name" type="text" v-model="from.fromName" placeholder="请输入用户名后开始聊天">
        </el-form-item>
        <el-form-item label="性别" prop="fromSex" style="position: absolute;left: 10px;top:80px">
          <el-radio v-model="from.fromSex" :label="1" size="large">男</el-radio>
          <el-radio v-model="from.fromSex" :label="0" size="large">女</el-radio>
        </el-form-item>
        <br>
        <el-row style="position: absolute;top:140px;left:90px">
          <el-col :span="24">
            <el-form-item>
              <el-button @click="getConnect" size="large" type="primary">开始聊天</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-if="isChat" style="width: 100%">
      <div class="chat-body"
           v-loading="macting"
           element-loading-text="正在匹配好友聊天..."
           :element-loading-spinner="svg"
           element-loading-svg-view-box="-10, -10, 50, 50"
           element-loading-background="rgba(255, 209, 255, 1)"
      >
        <div class="chat-header border-bottom py-xl-4 py-md-3 py-2">
          <div class="container-xxl">
            <div class="row align-items-center">
              <div class="col-6 col-xl-4">
                <div class="media">
                  <div class="avatar me-3">
                    <div class="avatar rounded-circle no-image bg-primary text-light">
                      <span><em class="zmdi zmdi-comment-text"></em></span>
                    </div>
                  </div>
                  <div class="media-body overflow-hidden">
                    <div class="d-flex align-items-center mb-1">
                      <h6 class="text-truncate mb-0 me-auto">{{from.toName}}
                        <span v-if="from.toSex===1" style="color:#0dcaf0">♂</span>
                        <span v-else style="color: #f68084">♀</span>
                      </h6>

                    </div>
                    <div v-if="from.chatUsers && from.chatUsers.length>=2" class="text-truncate"><em class="zmdi zmdi-circle text-success"></em> 在线</div>
                    <div v-else class="text-truncate" style="color: red"><em class="zmdi zmdi-circle"></em> 离线</div>
                  </div>
                </div>
              </div>
              <div class="col-6 col-xl-8 text-end" @click="exit" v-if="from.fromName">
                你的昵称为:(
                <span v-if="from.fromSex===1 || from.fromSex === null" style="color: #0dcaf0">{{ from.fromName }}</span>
                <span v-else style="color: #f68084">{{ from.fromName }}</span>
                )
              </div>
            </div>
          </div>
        </div>

        <div class="chat-content">
          <div class="container-xxl">
            <ul class="list-unstyled py-4" >
              <li v-for="(item,index) in this.globleMsgList" :key="index" class="d-flex message" :class="{'right': this.name===item.fromName}">
                <div class="mr-lg-3 me-2" v-if="this.name!==item.fromName">
                  <div class="avatar sm rounded-circle bg-primary d-flex align-items-center justify-content-center">
                    <span><em class="zmdi zmdi-comment-text text-light"></em></span>
                  </div>
                </div>
                <div  class="message-body" >
                  <span class="date-time text-muted">{{ item.sendTime }}</span>
                  <div class="message-row d-flex align-items-center" :class="{'justify-content-end':this.name===item.fromName}">
                    <div class="message-content p-3" :class="{'border':this.name===item.fromName,'buttom':this.globleMsgList.length-1===index}">
                      {{item.msg}}
                    </div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <!--消息脚部-->
        <div class="chat-footer border-top py-xl-4 py-lg-2 py-2">
          <div class="container-xxl">
            <div class="row">
              <div class="col-12">
                <div class="input-group align-items-center">

                  <textarea  ref="send" v-model="from.sendMsg" style="resize:none"  autofocus rows="3" type="text" @keyup.enter="send" class="form-control border-0 pl-0" placeholder="编辑你需要发送的消息...">
                  </textarea>

                  <div class="input-group-append">
                      <span class="input-group-text border-0 pr-0">
                      <button @click="send"  class="btn btn-primary" style="background-color: #0d6efd">
                      <span class="d-md-inline-block me-2">发送</span>
                        <em class="zmdi zmdi-mail-send"></em>
                      </button>
                      </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'chat',
  mounted() {
    sessionStorage.clear()
    localStorage.clear()
  },
  data(){
    return{
      ws:null,
      isChat:false,
      macting:true,
      name:null,
      svg : `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `,
      msgData:{},
      oppositeMsg:[],
      selgMsg:[],
      globleMsgList: [],
      from:{
        fromName:null,
        msgList:[],
        chatUsers:null,
        refresh:false,
        fromSex:1,
        fromId:null,
        sendMsg:null,
        onlineNums:0,
        toId:null,
        toName:null,
        toSex:null,
      },
      rules: {
        fromName:[{required:true,message:"请输入昵称",trigger:'blur'}],
        fromSex:[{required:true,message:"请选择性别",trigger:'blur'}],
      }
    }
  },
  watch:{
    globleMsgList(){
      let dom = document.getElementsByClassName("buttom")[0];
      if(dom!==undefined && dom != null){
        dom.scrollIntoView({
          behavior: "smooth",  // 平滑过渡
        });
      }

    }
  },
  methods:{
    getConnect(){
      this.$refs['from'].validate((valid) => {
        if (valid) {
          this.ws = new WebSocket(`ws://localhost:3000/chat/${this.from.fromName}/${this.from.fromSex}`)
          sessionStorage.setItem("name",this.from.fromName)
          localStorage.setItem(this.from.fromName,this.ws)
          this.name = this.from.fromName
          this.ws.onopen = this.open
          this.ws.onclose = this.close
          this.ws.onerror = this.error
          this.ws.onmessage = this.getMessage
        } else {
          return false;
        }
      });
    },
    open(){
      this.isChat = true
      window.onunload=function(){
        console.log("关闭连接")
        this.ws.close()
      };
      window.onbeforeunload=function(){
        console.log("关闭连接")
        this.ws.close()
      };
    },
    exit(){
      this.$confirm('是否确认退出该聊天，聊天记录不会保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ws.close()
        this.isChat = false;
        this.macting = false;
      })
    },
    error(data){
      console.log("连接错误",data)
      this.ws.close()
    },
    getMessage(msg) {
      this.from = JSON.parse(msg.data)
      if (typeof this.from ==='string'){
        this.from = JSON.parse(this.from)
      }
      if (this.from.msgList && this.from.msgList.length>0){
          this.globleMsgList.push(this.from.msgList[this.from.msgList.length-1])
      }
      this.globleMsgList = new Set(this.globleMsgList)
      this.globleMsgList = Array.from(this.globleMsgList)
      this.from.sendMsg = ''
      this.$refs['send'].focus()
      if (this.from.onlineNums > 1 && this.from.chatUsers) {
        for(let chatUser of this.from.chatUsers){
          if (chatUser.username !== sessionStorage.getItem('name')) {
            this.from.toId = chatUser.userId
            this.from.toSex = chatUser.sex
            this.from.toName = chatUser.username
          } else {
            this.from.fromId = chatUser.userId
            this.from.fromSex = chatUser.sex
            this.from.fromName = chatUser.username
          }
        }
        this.macting = false
      }
    },
    close() {
      ElMessage.error('连接数已到上线，请稍后再试')
      this.macting = false
      this.isChat = false
      this.ws.close()
    },
    send(){
      if (this.from.sendMsg==='' || this.from.sendMsg===null){
        this.$message.warning('无法发送空消息');
        return;
      }
      let msgFrom = {
        toName:this.from.toName,
        toSex:this.from.toSex,
        toId:this.from.toId,
        msg:this.from.sendMsg,
        sendTime:new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate()+' '+new Date().getHours()+':'+new Date().getMinutes()+':'+new Date().getSeconds(),
        fromName:this.from.fromName,
        fromSex:this.from.fromSex,
        fromId:this.from.fromId,
      }
      if (!sessionStorage.getItem("msgList")){
        this.msgData = []
        if (msgFrom.fromId && msgFrom.fromName && msgFrom.toName && msgFrom.toId){
          this.msgData.push(msgFrom)
          sessionStorage.setItem("msgList",JSON.stringify(this.msgData))
        }
      }else {
        this.msgData = JSON.parse(sessionStorage.getItem("msgList"))
        if (msgFrom.fromId && msgFrom.fromName && msgFrom.toName && msgFrom.toId) {
          this.msgData.push(msgFrom)
          sessionStorage.setItem("msgList",JSON.stringify(this.msgData))
        }
      }
      this.from.msgList = this.msgData
      this.ws.send(JSON.stringify(this.from))
      this.from.sendMsg = ''
      this.$refs['send'].focus()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

.name {
  background-color: transparent;
  width: 200px;
  padding: 5px;
  text-indent: 10px;
  color: black;
  font-size: 20px;
  /*height: 45px;*/
  /*margin: 30px 30px 30px 5px;*/
  border-radius: 20px;
  outline: none;
  border: 1px solid rgb(213, 206, 139);
}

h1{
  font-weight: 100;
  color:#f68084
}
input::placeholder {
  color: #7b8292;
  font-size: 15px;
  font-weight: 100;
  font-style: italic;
}

.hello{
  width: 100%;
  height: 100vh;
}
.login {
  width: 100%;
  height: 100%;
  float: left;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);

}

</style>
